package com.pogita.cleancode.testprotectionjava;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pogita.cleancode.testprotectionjava.model.Result;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class MockResponseBodyUtils {
    static {
        Path responseBodyMockPath = Paths.get(System.getProperty("user.dir"), "src",
                "test", "resources", "rest-api", "payment-system.json");
        try (BufferedReader bufferedReader = Files.newBufferedReader(responseBodyMockPath)) {
            String config = bufferedReader.lines().collect(Collectors.joining());
            JSONObject jsonObject = JSON.parseObject(config);
            JSONArray apiArray = jsonObject.getJSONArray("api");
            responseBodyMap = apiArray.stream().map(obj -> (JSONObject) obj)
                    .collect(Collectors.toMap(jsonObj -> jsonObj.getString("key"), Function.identity()));
        } catch (IOException e) {
            responseBodyMap = new HashMap<>();
        }
    }

    private static Map<String, JSONObject> responseBodyMap;

    public static <T> Result<T> getResponseBody(String key) {
        return responseBodyMap.get(key).getJSONObject("responseBody").toJavaObject(Result.class);
    }
}
